import React from "react";
import { useForm } from "react-hook-form";
import { useRequest } from "ahooks";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Heading } from "@/components/ui/heading";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { zodResolver } from "@hookform/resolvers/zod";
import { ColumnDef, createColumnHelper, RowData } from "@tanstack/react-table";
import { ArrowUpDown, CalendarIcon } from "lucide-react";
import { Edit, MoreHorizontal, Trash } from "lucide-react";
import * as z from "zod";
import { AlertModal } from "@/components/modal/alert-modal";
import { VbpBatchI, VbpDeptDutyPreviewI } from "@/types";
import PageContainer from "@/components/layout/page-container";
import CustomDndTable from "@/components/ui/custom-dnd-table";
import { useToast } from "@/hooks/use-toast";
import { Plus } from "lucide-react";
import {
  generateVbpDeptDutyPreview,
  searchVbpDeptDutyPreviewList,
  deleteVbpDeptDutyPreview,
  updateVbpDeptDutyPreview,
  batchUseVbpDeptDutyPreview,
} from "@/api";
import { useSearchParams, Link } from "react-router-dom";

declare module "@tanstack/react-table" {
  interface TableMeta<TData extends RowData> {
    updateData: (rowIndex: number, columnId: string, value: unknown) => void;
  }
}

// Give our default column cell renderer editing superpowers!
const defaultColumn: Partial<ColumnDef<VbpDeptDutyPreviewI>> = {
  cell: ({ getValue, row: { index }, column: { id }, table }) => {
    const initialValue = getValue();
    // We need to keep and update the state of the cell normally
    const [value, setValue] = React.useState(initialValue);

    // When the input is blurred, we'll call our table meta's updateData function
    const onBlur = () => {
      table.options.meta?.updateData(index, id, value);
    };

    // If the initialValue is changed external, sync it up with our state
    React.useEffect(() => {
      setValue(initialValue);
    }, [initialValue]);

    return (
      <input
        value={value as string}
        onChange={(e) => setValue(e.target.value)}
        onBlur={onBlur}
      />
    );
  },
};

const formSchema = z.object({
  id: z.string().optional(),
  vbpBatchId: z.string({ required_error: "请先选择集采批次药品" }),
  deptYbName: z.string({ required_error: "请选择科室" }),
  hisCode: z.string({ required_error: "请选择药品代码" }),
  drugname: z.string({ required_error: "请选择药品名称" }),
  deptDutyAmount: z
    .number({ required_error: "请录入任务量" })
    .min(0)
    .max(1000000000000000),
});

type FormValuesT = z.infer<typeof formSchema>;

const page: React.FC = () => {
  const [searchParams] = useSearchParams();
  const { toast } = useToast();

  const [title, setTitle] = React.useState<string>("");
  const [description, setDescription] = React.useState<string>("");
  const [isGenerating, setIsGenerating] = React.useState<boolean>(false);
  const [isSubmitting, setIsSubmitting] = React.useState<boolean>(false);
  const [isAlertOpen, setIsAlertOpen] = React.useState<boolean>(false);
  const [isDialogOpen, setIsDialogOpen] = React.useState<boolean>(false);
  const [totalCount, setTotalCount] = React.useState<number>(0);
  const [vbpDeptDutyPreviewList, setVbpDeptDutyPreviewList] = React.useState<
    VbpDeptDutyPreviewI[]
  >([]);
  const [formData, setFormData] = React.useState<VbpDeptDutyPreviewI>();

  const { loading: loadingList, run } = useRequest(
    (paramsString: string) => searchVbpDeptDutyPreviewList(paramsString),
    {
      manual: true,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp, params: any) {
        setVbpDeptDutyPreviewList(resp.data.data);
        setTotalCount(resp.data.totalCount);
      },
      onError(e: any, params: any) {
        console.error("获取数据失败");
        toast({
          variant: "destructive",
          title: "数据获取失败",
          description: "请检查网络或联系系统管理员",
        });
      },
    }
  );

  React.useEffect(() => {
    run(searchParams.toString());
  }, [searchParams]);

  const onGenerateClick = (event: any) => {
    setIsGenerating(true);
    generateVbpDeptDutyPreview()
      .then((res: any) => {
        console.log(res);
        setIsGenerating(false);
        toast({
          variant: "success",
          title: "数据生成成功",
          description: "",
          duration: 1600,
        });
      })
      .catch((err) => {
        console.error(err);
        setIsGenerating(false);
        toast({
          variant: "destructive",
          title: "数据生成失败",
          description: "",
          duration: 1600,
        });
      });
  };

  const onUpdateClick = (event: any, data: VbpDeptDutyPreviewI) => {
    const processedData = Object.assign(
      {},
      defaultValues,
      Object.fromEntries(
        Object.entries(data).reduce((acc, [key, value]) => {
          if (value !== null) {
            acc.push([key, value]);
          }
          return acc;
        }, [] as [string, any][])
      )
    );
    console.log(processedData);
    setTitle("修改信息");
    // 避免将受控组件的值设置成null，否则会有警告，影响未知
    form.reset(processedData);
    setIsDialogOpen(true);
    run();
  };

  const onDeleteConfirm = (event: any, data: VbpDeptDutyPreviewI) => {
    try {
      setIsSubmitting(true);
      if (data.id) {
        deleteVbpDeptDutyPreview(data.id).then((res: any) => {
          console.log(data);
          console.log(res);
          toast({
            title: "删除成功",
            description: "",
          });
          run();
        });
      }
    } catch (error: any) {
      console.log(error);
      toast({
        title: "删除失败",
        description: "error",
      });
    } finally {
      setIsSubmitting(false);
      setIsAlertOpen(false);
    }
  };

  const columnHelper = createColumnHelper<VbpDeptDutyPreviewI>();
  const columns = [
    columnHelper.display({
      id: "select",
      header: (props) => {
        // console.log(props);
        if (props && props.table) {
          return (
            <Checkbox
              checked={props.table.getIsAllPageRowsSelected()}
              onCheckedChange={(value) =>
                props.table.toggleAllPageRowsSelected(!!value)
              }
              aria-label="Select all"
            />
          );
        } else {
          return <Checkbox aria-label="Select all" />;
        }
      },
      footer: (props) => props.column.id,
      cell: (props) => {
        if (props && props.row) {
          return (
            <Checkbox
              checked={props.row.getIsSelected()}
              onCheckedChange={(value) => props.row.toggleSelected(!!value)}
              aria-label="Select row"
            />
          );
        } else {
          return <Checkbox aria-label="Select row" />;
        }
      },
      enableHiding: true,
    }),
    columnHelper.accessor("id", {
      id: "id",
      header: "ID",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <Link
              to={"/medicine/info/" + row.getValue("id")}
              target="_blank"
              rel="noreferrer"
            >
              {row.getValue("id")}
            </Link>
          );
        }
      },
      enableSorting: false,
      enableHiding: false,
    }),
    columnHelper.accessor("vbpBatch.hisCode", {
      id: "vbpBatch.hisCode",
      header: "HIS代码",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          // console.log(row);
          return row.original.vbpBatch!.hisCode;
        }
      },
      enableSorting: true,
    }),
    columnHelper.accessor("vbpBatch.drugname", {
      id: "vbpBatch.drugname",
      header: "药品名称",
    }),
    columnHelper.accessor("vbpBatch.specification", {
      id: "vbpBatch.specification",
      header: "包装规格",
    }),
    columnHelper.accessor("deptYbName", {
      id: "deptYbName",
      header: "科室",
    }),
    columnHelper.accessor("deptAmountSum", {
      id: "deptAmountSum",
      header: "科室上年度统计",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <div>
              <span>
                {row.original.deptAmountSum}
                {row.original.vbpBatch?.miniUnit}
              </span>
            </div>
          );
        }
      },
    }),
    columnHelper.accessor("totalAmountSum", {
      id: "totalAmountSum",
      header: "全院上年度统计",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <div>
              <span>
                {row.original.totalAmountSum}
                {row.original.vbpBatch?.miniUnit}
              </span>
            </div>
          );
        }
      },
    }),
    columnHelper.display({
      id: "usePercentage",
      header: "科室上年度占比",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <div>
              <span>
                {`${(
                  (row.original.deptAmountSum / row.original.totalAmountSum) *
                  100
                ).toFixed(2)}%`}
              </span>
            </div>
          );
        }
      },
    }),
    columnHelper.accessor("totalDutyAmount", {
      id: "totalDutyAmount",
      header: "全院任务量",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <div>
              <span>
                {row.original.totalDutyAmount}
                {row.original.vbpBatch?.miniUnit}
              </span>
            </div>
          );
        }
      },
    }),
    columnHelper.accessor("deptDutyAmount", {
      id: "deptDutyAmount",
      header: "建议科室任务量",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <div>
              <span>
                {row.original.deptDutyAmount}
                {row.original.vbpBatch?.miniUnit}
              </span>
            </div>
          );
        }
      },
    }),
    columnHelper.display({
      header: "操作",
      id: "actions",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <>
              <AlertModal
                isOpen={isAlertOpen}
                onClose={() => setIsAlertOpen(false)}
                onConfirm={() => onDeleteConfirm(event, row.original)}
                loading={isSubmitting}
              />
              <DropdownMenu modal={false}>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" className="h-8 w-8 p-0">
                    <span className="sr-only">选项</span>
                    <MoreHorizontal className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuLabel></DropdownMenuLabel>
                  <DropdownMenuItem
                    onClick={() => onUpdateClick(event, row.original)}
                  >
                    <Edit className="mr-2 h-4 w-4" /> 更新
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => setIsAlertOpen(true)}>
                    <Trash className="mr-2 h-4 w-4" /> 删除
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </>
          );
        }
      },
    }),
  ];

  const defaultValues = {
    id: undefined,
    vbpBatchId: "",
    deptDutyAmount: 0,
  };

  // 表单部分
  const form = useForm<FormValuesT>({
    resolver: zodResolver(formSchema),
    defaultValues: defaultValues,
  });

  const handleFormSubmit = async (data: FormValuesT) => {
    console.log(data);
    try {
      setIsSubmitting(true);
      if (data.id) {
        updateVbpDeptDutyPreview(data).then((res) => {
          run(searchParams.toString());
        });
      }
      setIsSubmitting(false);
      setIsDialogOpen(false);
      form.reset(defaultValues);
      toast({
        variant: "success",
        title: "数据提交成功",
        description: "",
        duration: 1600,
      });
    } catch (error: any) {
      toast({
        variant: "destructive",
        title: "数据提交失败",
        description: "请检查网络或联系系统管理员",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleBatchSubmit = (selections: any) => {
    console.log(selections);
    return new Promise((resolve, reject) => {
      if (selections.length) {
        const data = selections.map((selection: any) => selection.original);
        console.log(data);
        batchUseVbpDeptDutyPreview(data).then(
          (res: any) => {
            console.log(res);
            resolve(res);
            run(searchParams.toString());
            toast({
              variant: "success",
              title: "数据提交成功",
              description: "",
              duration: 3000,
            });
          },
          (err: any) => {
            console.log(err);
            reject(err);
            toast({
              variant: "destructive",
              title: "数据提交失败",
              description: "请检查网络或联系系统管理员",
              duration: 3000,
            });
          }
        );
      } else {
        reject("no files");
      }
    });
  };

  return (
    <PageContainer>
      <div className="space-y-4">
        {/* <Breadcrumbs items={breadcrumbItems} /> */}

        <div className="flex items-start justify-between">
          <Heading title={`集采科室任务分配`} description="" />
          <Button
            variant="outline"
            className="p-2 rounded-md"
            onClick={onGenerateClick}
            disabled={isGenerating}
          >
            <Plus className="mr-2 h-4 w-4" />
            批量预生成
          </Button>
        </div>
        <Separator />

        <CustomDndTable
          defaultFilterColumn="vbpBatch.drugname"
          columns={columns}
          initColumnVisibility={{ id: false }}
          data={vbpDeptDutyPreviewList}
          loading={loadingList}
          totalCount={totalCount}
          showImportButton={false}
          showBatchSubmit={true}
          onBatchSubmit={handleBatchSubmit}
        />

        <Dialog
          open={isDialogOpen}
          onOpenChange={() => setIsDialogOpen(!isDialogOpen)}
        >
          <DialogContent className="max-w-3xl h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle></DialogTitle>
              <DialogDescription></DialogDescription>
            </DialogHeader>
            <div className="flex items-center justify-between">
              <Heading title={title} description={description} />
            </div>
            <Separator />
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(handleFormSubmit)}
                className="w-full space-y-8"
              >
                <div className="flex flex-col gap-4">
                  {formData && formData.id ? (
                    <FormField
                      control={form.control}
                      name="id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>ID</FormLabel>
                          <FormControl>
                            <Input
                              placeholder="id"
                              {...field}
                              disabled={formData && formData.id ? true : false}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  ) : (
                    <></>
                  )}
                  <FormField
                    control={form.control}
                    name="vbpBatchId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>集采批次药品</FormLabel>
                        <FormControl>
                          <Input
                            disabled={true}
                            placeholder="集采批次药品"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="hisCode"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>药品代码</FormLabel>
                        <FormControl>
                          <Input
                            disabled={true}
                            placeholder="药品代码"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="drugname"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>药品名称</FormLabel>
                        <FormControl>
                          <Input
                            disabled={true}
                            placeholder="药品名称"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="deptYbName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>科室名称</FormLabel>
                        <FormControl>
                          <Input
                            disabled={true}
                            placeholder="科室名称"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="deptDutyAmount"
                    render={({ field: { onChange, value } }) => (
                      <FormItem>
                        <FormLabel>科室任务量</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            disabled={isSubmitting}
                            placeholder="科室任务量"
                            // {...field}
                            onChange={(e) => onChange(e.target.valueAsNumber)}
                            value={value}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <Button
                  disabled={isSubmitting}
                  className="ml-auto"
                  type="submit"
                >
                  提交
                </Button>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      </div>
    </PageContainer>
  );
};

export default page;
